/* eslint indent: ["off"] */
/* eslint space-before-function-paren: ["off"] */

// jjy connectionLimit 25,  用时: 20.759 秒
// jjy connectionLimit 50,  用时: 18.043 秒
// jjy connectionLimit 100, 用时: 18.855 秒
const insertCurrentGroupInfos = async (pool, groupArray, flatGroupMap, history_results, table_name) => {
  await Promise.all(
    history_results.map(async (history_item) => {
      const { id: historyResultId, time, number } = history_item

      const connection = await pool.getConnection()

      // 开始一个事务
      await connection.beginTransaction()

      try {
        // 批量插入 current_group_infos 数据
        const currentGroupInfos = groupArray.map((info) => {
          const subIndex = flatGroupMap[info.group_name].findIndex((sub_array) =>
            sub_array.map(Number).includes(Number(number))
          )
          const subArray = JSON.stringify(flatGroupMap[info.group_name][subIndex])

          return [historyResultId, time, number, info.group_name, info.group_type, subIndex, subArray]
        })

        // 使用批量插入
        await connection.query(
          `INSERT INTO ${table_name} (history_result_id, time, number, group_name, group_type, sub_index, sub_array) VALUES ?`,
          [currentGroupInfos]
        )

        // console.log(`插入 current_group_infos 完成：${currentGroupInfos.length} 条`)

        // 提交事务
        await connection.commit()

        // console.log(`插入${groupArray.length}条数据`)
      } catch (err) {
        // 出错时回滚事务
        await connection.rollback()
        console.error('插入数据时发生错误:', err)
      } finally {
        // 释放连接
        connection.release()
      }

      // console.log(`${history_item.id} 插入完成`)
    })
  )
}
module.exports = { insertCurrentGroupInfos }
